package com.example.back.controller;

import cn.hutool.core.io.FileUtil;
import com.example.back.common.AuthAccess;
import com.example.back.common.Result;
import com.example.back.entity.ProjectFile;
import com.example.back.service.ProjectFileService;
import com.example.back.utils.StringUtil;
import org.apache.logging.log4j.message.ReusableMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author Jm
 * @date 2024/7/14
 */
@RestController
@RequestMapping("/file")
public class FileController
{
    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    @Autowired
    private ProjectFileService projectFileService;

    private static final String ROTE_PATH = System.getProperty("user.dir") + File.separator + "files";

    @AuthAccess
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException
    {
        //文件的原始名称
        String originalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(originalFilename);
        // 文件的后缀
        String extName = FileUtil.extName(originalFilename);

        String newFileName = StringUtil.generateUUID() + "." +extName;
        String fileRealPath = ROTE_PATH + File.separator + newFileName;
        File saveFile = new File(fileRealPath);
        if(!saveFile.getParentFile().exists())
        {
            FileUtil.mkdir(saveFile.getParentFile());
        }
        file.transferTo(saveFile);
        String url = "http://" + ip + ":" + port + "/file/download/" + newFileName;
        return Result.success(url);
    }

    @AuthAccess
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException
    {
        String filePath = ROTE_PATH + File.separator + fileName;
        if(!FileUtil.exist(filePath))
        {
            return;
        }
//        byte[] bytes = FileUtil.readBytes(filePath);
//        ServletOutputStream outputStream = response.getOutputStream();
//        outputStream.write(bytes);
//        outputStream.flush();
//        outputStream.close();

        InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }


    @PostMapping("/delete")
    public Result deleteFile(@RequestBody ProjectFile projectFile)
    {
        String[] strList = projectFile.getPath().split("/");
        String fileName = strList[strList.length - 1];
        String filePath = ROTE_PATH + File.separator + fileName;
        File file = new File(filePath);
        if(FileUtil.exist(file))
        {
            FileUtil.del(file);
        }
        projectFileService.removeById(projectFile);
        return Result.success();
    }


    @PostMapping("/addFile")
    public Result addFile(@RequestBody ProjectFile projectFile)
    {
        projectFileService.save(projectFile);
        return Result.success();
    }
}
